package com.yy.wga.mp.module.pay.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yy.wga.mp.module.pay.entity.pojo.PayOrderDO;
import com.yy.wga.mp.module.pay.request.third.WechatRefundNotifyDecodeRequest;
import com.yy.wga.mp.module.pay.service.PayOrderService;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.mp.common.utils.common.StringUtils;
import com.yy.wga.mp.module.pay.client.enums.EPayOrderStatus;
import com.yy.wga.mp.module.pay.event.PayCallbackEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author hongfeng
 * @date 2021/5/25
 * @desc
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PayRefundCallbackManagerService {

    private final PayOrderService payOrderService;
    private final ApplicationEventPublisher eventPublisher;

    /**
     * 支付回调逻辑
     * @param refundNotifyDTO 回调内容
     */
    @Transactional(rollbackFor = Exception.class)
    public void refundNotify(WechatRefundNotifyDecodeRequest refundNotifyDTO) {
        // 校验订单是否存在
        PayOrderDO payOrder = payOrderService.getOne(new LambdaQueryWrapper<PayOrderDO>()
                .eq(PayOrderDO::getPayOrderNo, refundNotifyDTO.getOutTradeNo()));
        if (payOrder == null) {
            throw new BusinessException("订单不存在");
        }
        if (!payOrder.getStatus().equals(EPayOrderStatus.REFUND.getType())) {
            throw new BusinessException("订单不处于退款中状态");
        }

        // 修改支付订单
        LambdaUpdateWrapper<PayOrderDO> updateWrapper = new LambdaUpdateWrapper<PayOrderDO>()
                .eq(PayOrderDO::getId, payOrder.getId());
        updateWrapper.set(PayOrderDO::getPayOrderNo, refundNotifyDTO.getOutTradeNo());
        updateWrapper.set(PayOrderDO::getStatus, refundNotifyDTO.getRefundStatus().equals("SUCCESS") ? 5 : 2);
        updateWrapper.set(StringUtils.isNotBlank(refundNotifyDTO.getTransactionId()), PayOrderDO::getTransactionId, refundNotifyDTO.getTransactionId());
        payOrderService.update(updateWrapper);

        // 退款回调
        PayCallbackEvent payCallbackEvent = new PayCallbackEvent(this);
        payCallbackEvent.setAppKey(payOrder.getAppKey());
        payCallbackEvent.setOrderNo(payOrder.getOrderNo());
        payCallbackEvent.setPayOrderNo(payOrder.getPayOrderNo());
        // 退款状态 1、未退款 2、申请退款 3、退款中 4、退款成功 5、退款拒绝
        if (refundNotifyDTO.getRefundStatus().equals("SUCCESS")) {
            payCallbackEvent.setRefundStatus(4);
        } else {
            payCallbackEvent.setRefundStatus(1);
        }
        eventPublisher.publishEvent(payCallbackEvent);
    }
}
